package mqtt

import (
	"fmt"
	"iot-base/common/config"
	"sync"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

func connLostHandler(c MQTT.Client, err error) {
	fmt.Printf("Connection lost, reason: %v\n", err)
}
func onConnectHandler(c MQTT.Client) {
	fmt.Printf("Connection is ok\n")
}

//CreateClient 创建客户端
func CreateClient(selfID string) MQTT.Client {
	//opts := MQTT.NewClientOptions().AddBroker("tcp://139.159.183.182:8006")
	//opts := MQTT.NewClientOptions().AddBroker("tcp://192.168.1.141:1883")
	//opts := MQTT.NewClientOptions().AddBroker("tcp://192.168.1.181:1883")
	return CreateClientEx(selfID, nil)
}

var mapLock = new(sync.RWMutex)
var clientMap = make(map[string]MQTT.Client)

//GetClient 获取client
func GetClient(mqttAddr string) MQTT.Client {
	if mqttAddr == "" {
		mqttAddr = config.MQTTOption.Addr
	}
	mapLock.RLock()
	c, _ := clientMap[mqttAddr]
	mapLock.RUnlock()
	return c

}

//CreateClientEx 创建客户端
func CreateClientEx(id string, onConnectFun func(c MQTT.Client)) MQTT.Client {
	fmt.Println("begin client-----------")
	return CreateClientByParam("", "", "", id, onConnectFun)
}

//CreateClientByParam 创建客户端
func CreateClientByParam(mqttAddr string, un string, pwd string, selfID string, onConnectFun func(c MQTT.Client)) MQTT.Client {
	//opts := MQTT.NewClientOptions().AddBroker("tcp://139.159.183.182:8006")
	//opts := MQTT.NewClientOptions().AddBroker("tcp://192.168.1.141:1883")
	//opts := MQTT.NewClientOptions().AddBroker("tcp://192.168.1.181:1883")

	if mqttAddr == "" {
		mqttAddr = config.MQTTOption.Addr
	}
	c := GetClient(mqttAddr)
	if c != nil {
		return c
	}

	opts := MQTT.NewClientOptions().AddBroker(mqttAddr)
	opts.SetAutoReconnect(true)
	opts.SetCleanSession(false)
	opts.SetConnectTimeout(30 * time.Second)
	opts.SetKeepAlive(60 * time.Second)
	//opts.SetMessageChannelDepth(5)
	if selfID == "" {
		selfID = config.SelfOption.ID
	}
	if un == "" {
		un = config.MQTTOption.UN
	}
	if pwd == "" {
		pwd = config.MQTTOption.PWD
	}
	fmt.Println("clientid ", selfID, mqttAddr, un, pwd)
	opts.SetClientID(selfID)
	opts.SetUsername(un)
	opts.SetPassword(pwd)

	opts.SetConnectionLostHandler(connLostHandler)
	opts.SetOnConnectHandler(func(client MQTT.Client) {
		mapLock.Lock()
		clientMap[mqttAddr] = client
		mapLock.Unlock()
		if onConnectFun != nil {
			onConnectFun(client)
		}
		fmt.Println("--------------------mqtt client ---------succeed")
		//reRegisterHandler(client)
		//reRegisterWithPattern(mqttAddr)
	})

	//为默认消息处理程序
	var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
		//fmt.Printf("no TOPIC: %s\n", msg.Topic())
		//fmt.Printf("no MSG: %s\n", msg.Payload())
	}
	opts.SetDefaultPublishHandler(f)

	//使用上面的ClientOptions创建并启动客户端
	c = MQTT.NewClient(opts)

	if token := c.Connect(); token.Wait() && token.Error() != nil {
		fmt.Println("error", token.Error())
		return nil
	}

	return c
}
